// 完成了同步
// class MyPromise {
//   constructor(executor) {
//     this.state = 'pending'
//     this.value = ''
//     this.reason = ''
//     let resolve = (value) => {
//       console.log("这里是测试resolve传入的形参", value);
//       if (this.state === 'pending') {
//         this.state = 'fullFilled'  //改变状态
//         this.value = value   //存入形参的值
//       }
//     }
//     let reject = (reason) => {
//       if (this.state === 'pending') {
//         this.state = 'rejected'
//         this.reason = reason
//       }
//     }
//     try {
//       executor(resolve, reject)
//     }
//     catch {
//       reject(reason)
//     }
//   }
//   then(onFullFilled, onRejected) {
//     if (this.state = 'fullFilled') {
//       onFullFilled(this.value)
//     }
//     if (this.state = 'rejected') {
//       onRejected(this.reason)
//     }
//   }
// }

/**
 * 发布订阅模式
 * * 两个回调,所以需要两个数组去存储
 * 在哪里存储？
 * * 因为如果存在异步的情况的话,执行的顺序是then-->resolve/reject
 * * 所以我们需要在then方法里去将成功与失败的回调存储到相应的数组中
 * * 所以就是在state的是pending的情况下去存储回调
 * * 在执行resolve/reject方法时候,将相应数组的回调依次调用
 */

class MyPromise {
  constructor(executor) {
    this.state = 'pending'
    this.value = ''
    this.reason = ''
    this.onResolvedCallback = []
    this.onRejectedCallback = []
    let resolve = (value) => {
      if (this.state === 'pending') {
        this.state = 'fullFilled'  //改变状态
        this.value = value   //存入形参的值
        this.onResolvedCallback.forEach(fn => {
          fn()
        })
      }
    }
    let reject = (reason) => {
      if (this.state === 'pending') {
        this.state = 'rejected'
        this.reason = reason
        this.onRejectedCallback.forEach(fn => fn())
      }
    }
    try {
      executor(resolve, reject)
    }
    catch {
      reject(reason)
    }
  }
  then(onFullFilled, onRejected) {
    if (this.state === 'fullFilled') {
      onFullFilled(this.value)
    }
    if (this.state === 'rejected') {
      onRejected(this.reason)
    }
    if (this.state === 'pending') {
      this.onResolvedCallback.push(() => {
        onFullFilled(this.value)
      })
      this.onRejectedCallback.push(() => {
        onRejected(this.reason)
      })
    }
  }
}



module.exports = {
  MyPromise
}